package com.yanqu.road.server.gameplayer.module.activity.huashigang;

import com.yanqu.road.entity.activity.ActivityDisperseGoldInfo;
import com.yanqu.road.entity.activity.ActivityDisperseGoldResult;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangFloorCellData;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangFloorConfig;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangNewConfig;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangUserFloor;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.config.goods.OpenGoodsBagResult;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.enums.activity.huashigang.eHuaShiGangMessageType;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.player.UserPatronsSkill;
import com.yanqu.road.logic.bussiness.player.activity.auto.reward.UserHuaShiGangBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.HuaShiGangPb;
import com.yanqu.road.pb.huashigang.HuaShiGangProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.DecorationModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.logic.battle.BattleManager;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.DigMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.huashigang.HuaShiGangMgr;
import com.yanqu.road.server.manger.config.GoodsBagMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author wpj
 * @Date 2020/10/11
 */
public class HuaShiGangModule extends GeneralModule {

    Map<Integer, HuaShiGangUserFloor> floorMap;

    public Map<Integer, HuaShiGangUserFloor> getFloorMap() {
        return floorMap;
    }

    public void setFloorMap(Map<Integer, HuaShiGangUserFloor> floorMap) {
        this.floorMap = floorMap;
    }

    public HuaShiGangModule(GamePlayer player) {
        super(player);
    }

    @Override
    public void afterLogin() {
       sendConfigToClient();
    }

    public void sendConfigToClient() {
        ActivityInfo activityInfo = HuaShiGangMgr.getActivityInfo();
        if (activityInfo != null) {
            if (ActivityMgr.activityInShowTime(activityInfo)) {
                player.sendPacket(ClientProtocol.U_HUA_SHI_GANG_ACTIVITY, HuaShiGangPb.getHuaShiGangActivity(activityInfo.getActivityId(), HuaShiGangMgr.getEventsPb(player.getUserInfo().getLanguage()), HuaShiGangMgr.getIntegerHuaShiGangFloorConfigMap()));
            }
        }
    }

    @Override
    public boolean loadData() {
        floorMap = UserHuaShiGangBusiness.getHuaShiGangUserFloor(player.getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        for (HuaShiGangUserFloor floor : floorMap.values()) {
            if (floor.isInsertOption()) {
                UserHuaShiGangBusiness.addData(floor);
            } else if (floor.isUpdateOption()) {
                UserHuaShiGangBusiness.updateData(floor);
            }
        }
        return true;
    }

    /**
     * 同步商店信息数据给客户端
     */
    public void syncHuaShiGangShopData(int code) {
        ActivityInfo activityInfo = HuaShiGangMgr.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }

        HuaShiGangUserFloor userdata = getFloorData(activityInfo.getActivityId());
        if (userdata == null) {
            log.error("floor data is null. {}", activityInfo.getActivityId());
            return;
        }
        HuaShiGangProto.HuaShiGangShopData.Builder builder = HuaShiGangProto.HuaShiGangShopData.newBuilder();
        builder.setCurrentMallId(userdata.getCurrentMall());
        for (Map.Entry<Integer, Long> entry : userdata.getMallMap().entrySet()) {
            int mallId = entry.getKey();
            long mallTime = entry.getValue();
            int mallTimes = userdata.getMallTimes(mallId);

            if (mallTimes <= 0) {
                continue;
            }

            HuaShiGangProto.HuaShiGangMallEntity.Builder msg = HuaShiGangPb.parseHuaShiGangMallEntity(mallId, mallTime, mallTimes);
            builder.addMallInfo(msg);
        }
        player.sendPacket(code, builder);
    }

    /**
     * 花石纲活动数据
     * @param activityId
     * @return
     */
    public HuaShiGangUserFloor getFloorData(int activityId) {
        Map<Integer, HuaShiGangFloorConfig> map = HuaShiGangMgr.getIntegerHuaShiGangFloorConfigMap();
        if (map == null) {
            return null;
        }
        if (!floorMap.containsKey(activityId)) {
            HuaShiGangUserFloor huaShiGangUserFloor = new HuaShiGangUserFloor();
            huaShiGangUserFloor.setUserId(player.getUserId());
            huaShiGangUserFloor.setFloor(1);
            huaShiGangUserFloor.setActivityId(activityId);

            HuaShiGangFloorConfig config =  map.get(1);
            huaShiGangUserFloor.setCellDataList(DigMgr.buildCellDataList(config));
            huaShiGangUserFloor.setGotBigReward(0);
            huaShiGangUserFloor.setInsertOption();
            floorMap.put(activityId, huaShiGangUserFloor);
        }

        return floorMap.get(activityId);
    }

    /**
     * 检查宝库数据 看是否进入下一层
     */
    public Property checkFloor(int activityId, int boxId) {
        HuaShiGangUserFloor userFloor = floorMap.get(activityId);
        if (userFloor == null) {
            return new Property();
        }

        HuaShiGangNewConfig newConfig = HuaShiGangMgr.getNewConfig();
        if (newConfig == null) {
            return new Property();
        }

        Map<Integer, HuaShiGangFloorConfig> map = HuaShiGangMgr.getIntegerHuaShiGangFloorConfigMap();
        if (map == null) {
            return new Property();
        }

        HuaShiGangFloorConfig nowConfig = HuaShiGangMgr.getHuaShiGangFloorConfig(userFloor.getFloor());
        if (userFloor.getCellDataList().size() != 9) {
            // 数据异常
            userFloor.setCellDataList(DigMgr.buildCellDataList(nowConfig));
            userFloor.setUpdateOption();
            return new Property();
        }

        boolean next = false;
        for (HuaShiGangFloorCellData cellData : userFloor.getCellDataList()) {
            if (cellData.isOpen() && cellData.isSpecial()) {
                // 判断特殊奖励是否被触发
                next = true;
                break;
            }
        }

        if (!next) {
            for (HuaShiGangFloorCellData cellData : userFloor.getCellDataList()) {
                if (!cellData.isOpen()) {
                    // 如果还有格子未被打开则 不进行生成
                    next = false;
                    break;
                }
            }
        }

        boolean reset = false;
        if (next) {
            userFloor.setFloor(userFloor.getFloor() + 1);
            if (HuaShiGangMgr.getIntegerHuaShiGangFloorConfigMap().get(userFloor.getFloor()) == null) {
                // 如果找不到配置表示已达到最高级
                userFloor.setFloor(1);
                reset = true;
            }
            userFloor.setCellDataList(DigMgr.buildCellDataList(HuaShiGangMgr.getIntegerHuaShiGangFloorConfigMap().get(userFloor.getFloor())));
            userFloor.setUpdateOption();
        }

        if (reset) {
            userFloor.setGotBigReward(1);
            if (boxId > 0) {
                OpenGoodsBagResult result = GoodsBagMgr.getRandomGoods(boxId);
                if (result.getReward().getGoods().size() > 0) {
                    player.getModule(CurrencyModule.class).addCurrency(result.getReward(), eLogMoneyType.HuaShiGang, eLogMoneyType.HuaShiGangDIG);
                    StringBuilder rewardBuilder = new StringBuilder();
                    rewardBuilder.append(eHuaShiGangMessageType.DIG_FLOOR_ALL_PASS.getValue());
                    rewardBuilder.append(GameConfig.TALK_SEPARATOR);
                    rewardBuilder.append(PropertyHelper.parsePropertyToString(result.getReward()));
                    WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(), eMessageType.HuaShiGangSystemMsg.getValue(), eChatContentType.Common.getContentType(), rewardBuilder.toString(), System.currentTimeMillis(), activityId, null);
                    WorldMessageMgr.sendCrossActivityChat(msg);
                }
                return result.getReward();
            } else {
                Property reward = PropertyHelper.randomPropertyByListList(newConfig.getDigPassRewardList());
                if (!reward.isNothing()) {
                    player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.HuaShiGang, eLogMoneyType.HuaShiGangDIG);
                    StringBuilder rewardBuilder = new StringBuilder();
                    rewardBuilder.append(eHuaShiGangMessageType.DIG_FLOOR_ALL_PASS.getValue());
                    rewardBuilder.append(GameConfig.TALK_SEPARATOR);
                    rewardBuilder.append(PropertyHelper.parsePropertyToString(reward));
                    WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(), eMessageType.HuaShiGangSystemMsg.getValue(), eChatContentType.Common.getContentType(), rewardBuilder.toString(), System.currentTimeMillis(), activityId, null);
                    WorldMessageMgr.sendCrossActivityChat(msg);
                }
                return reward;
            }
        }

        return new Property();
    }


    /**
     * 通知商城
     */
    public void notifyShopEvent() {
        ActivityInfo activityInfo = HuaShiGangMgr.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }

        HuaShiGangUserFloor userdata = getFloorData(activityInfo.getActivityId());
        if (userdata == null) {
            return;
        }

        List<MallInfo> list = getMallList(activityInfo.getActivityId());
        if (list.size() > 0) {
//            if (userdata.getNextMall() > 0) {
//                // 当有下一个礼包时 则用下一个礼包id来设置给到当前id
//                userdata.setCurrentMall(userdata.getNextMall());
//                userdata.setNextMall(0);
//            } else {
//                // 下一个礼包id为空时 说明需要读vip等级
//                userdata.setCurrentMall(getVipLevelMallId(list));
//            }
            int triggerMallId = getVipLevelMallId(list);
            if(triggerMallId > 0) {
                long lastMallTime = userdata.getMallTime(triggerMallId);
                long nowTime = System.currentTimeMillis();
                if (nowTime > (lastMallTime + HuaShiGangMgr.getNewConfig().getRmbMallTime())) {
                    userdata.clearMallTimes(triggerMallId);
                }
            }
            userdata.setCurrentMall(triggerMallId);
        }
        syncHuaShiGangShopData(ClientProtocol.U_HUA_SHI_GANG_NOTIFY_SHOP_TO_CLIENT);
    }


    /**
     * 获取VIP等级对应的mallId
     * @param list
     * @return
     */
    public int getVipLevelMallId(List<MallInfo> list) {
        int vipLevel = VipMgr.getVipLv(player.getModule(PlayerModule.class).getUserInfo().getVipExp());

        Set<Integer> typeSet = new HashSet<>();
        for (MallInfo mallInfo : list) {
            List<Integer> paramList = StringUtils.stringToIntegerList(mallInfo.getExtendParam(), "\\|");
            typeSet.add(paramList.get(0));
        }

        int mallId = 0;
        if (typeSet.size() > 0) {
            // 随机一个类型
            List<Integer> typeList = new ArrayList<>(typeSet);
            int type = typeList.get(new Random().nextInt(typeList.size()));


            for (MallInfo mallInfo : list) {
                List<Integer> paramList = StringUtils.stringToIntegerList(mallInfo.getExtendParam(), "\\|");

                if (type == paramList.get(0) && vipLevel >= paramList.get(1)) {
                    mallId = mallInfo.getMallId();
                    break;
                }
            }
        }
        return mallId;
    }


    /**
     * 获取商城列表
     * @param activityId
     * @return
     */
    public List<MallInfo> getMallList(int activityId) {
        Map<Integer, MallInfo> mallInfoMap = NormalActivityMgr.getMallInfoTypeMap(activityId, eShopType.HuaShiGangMoneyMall.getValue());
        List<MallInfo> list = new ArrayList<>(mallInfoMap.values());
        list.sort(new Comparator<MallInfo>() {
            @Override
            public int compare(MallInfo o1, MallInfo o2) {
                int l2 = Integer.valueOf(StringUtils.stringToIntegerList(o2.getExtendParam(), "\\|").get(1));
                int l1 = Integer.valueOf(StringUtils.stringToIntegerList(o1.getExtendParam(), "\\|").get(1));
                if (l2 == l1) {
                    return 0;
                } else if (l2 > l1) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        return list;
    }

    /**
     * 跳过商店事件
     */
    public void giveUpShopEvent() {
        ActivityInfo activityInfo = HuaShiGangMgr.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }

        HuaShiGangUserFloor userdata = getFloorData(activityInfo.getActivityId());
        if (userdata == null) {
            return;
        }

        if (userdata.getCurrentMall() > 0) {
            // 未购买的需要处理一下 放进未购买列表
            long lastMallTime = userdata.getMallTime(userdata.getCurrentMall());
            long nowTime = System.currentTimeMillis();
            if (nowTime > (lastMallTime + HuaShiGangMgr.getNewConfig().getRmbMallTime())) {
                userdata.clearMallTimes(userdata.getCurrentMall());
            }
            userdata.setMallTime(userdata.getCurrentMall(), nowTime);
            userdata.addMallTimes(userdata.getCurrentMall(), 1);
            // 设置nextMallId
//            List<MallInfo> list = getMallList(activityInfo.getActivityId());
//            if (list.size() > 0) {
//
//                // 放弃后到上一个礼包等级
//                int newMallId = getNewMallId(userdata.getCurrentMall(), list, false);
//                userdata.setNextMall(newMallId);
//            }

            // 重置当前的商品id为0
            userdata.setCurrentMall(0);
        }
        syncHuaShiGangShopData(ClientProtocol.U_HUA_SHI_GANG_NOTIFY_SHOP_TO_CLIENT);
    }

    /**
     * 获取礼包等级
     * @param mallId
     * @param list
     * @return
     */
    public int getNewMallId(int mallId, List<MallInfo> list, boolean add) {
        // 当前商品等级
        int level = 0;
        for (MallInfo mallInfo : list) {
            if (mallId == mallInfo.getMallId()) {
                List<Integer> paramList = StringUtils.stringToIntegerList(mallInfo.getExtendParam(), "\\|");
                level = paramList.get(2);
                break;
            }
        }

        int realLevel = level;
        if (add) {
            realLevel ++;
        } else {
            realLevel --;
        }

        // 判断是否有符合条件的商品
        for (MallInfo mallInfo : list) {
            if (mallId == mallInfo.getMallId()) {
                List<Integer> paramList = StringUtils.stringToIntegerList(mallInfo.getExtendParam(), "\\|");
                if (realLevel == paramList.get(2)) {
                    level = realLevel;
                    break;
                }
            }
        }

        if (level == 0) {
            return mallId;
        }

        List<MallInfo> targetList = new ArrayList<>();
        for (MallInfo mallInfo : list) {
            List<Integer> paramList = StringUtils.stringToIntegerList(mallInfo.getExtendParam(), "\\|");
            if (paramList.get(2) == level) {
                targetList.add(mallInfo);
            }
        }

        return targetList.get(new Random().nextInt(targetList.size())).getMallId();

    }

    /**
     * 商城购买
     * @param mallId
     */
    public void shopBuy(int mallId) {
        try {
            ActivityInfo activityInfo = HuaShiGangMgr.getActivityInfo();
            if (!ActivityMgr.activityInShowTime(activityInfo)) {
                return;
            }

            HuaShiGangUserFloor userdata = getFloorData(activityInfo.getActivityId());
            if (userdata == null) {
                return;
            }

            if (userdata.getMallTimes(mallId) > 0) {
                // 优先扣背包的
                userdata.reduceMallTimes(mallId, 1);
                if (userdata.getMallTimes(mallId) <= 0) {
                    userdata.removeMall(mallId);
                }
            } else if (mallId == userdata.getCurrentMall()) {
                userdata.setCurrentMall(0);
            }

            syncHuaShiGangShopData(ClientProtocol.U_HUA_SHI_GANG_NOTIFY_SHOP_TO_CLIENT);
        } catch (Exception ex) {
            log.error(ex);
        } finally {

        }

    }

    /**
     * 是否可下单
     * @param mallId
     * @return
     */
    public boolean canPrecharge(int mallId) {
        ActivityInfo activityInfo = HuaShiGangMgr.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return false;
        }

        HuaShiGangUserFloor userdata = getFloorData(activityInfo.getActivityId());
        if (userdata == null) {
            return false;
        }

        if (userdata.getCurrentMall() == mallId) {
            return true;
        }

        if (System.currentTimeMillis() <= (userdata.getMallTime(mallId) + HuaShiGangMgr.getNewConfig().getRmbMallTime())) {
                return true;
        }
        return false;
    }

    /**
     * 是否可以到账成功 不判断时间 只要有就可以到账
     * @param mallId
     * @return
     */
    public boolean canChargeSucceed(int mallId) {
        ActivityInfo activityInfo = HuaShiGangMgr.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return false;
        }

        HuaShiGangUserFloor userdata = getFloorData(activityInfo.getActivityId());
        if (userdata == null) {
            return false;
        }

        if (userdata.getCurrentMall() == mallId || userdata.getMallMap().containsKey(mallId)) {
            return true;
        }

        return false;
    }

    /**
     * 击杀蔡京触发送财
     * @param activityInfo 活动信息
     * @return ActivityDisperseGoldResult
     */
    public ActivityDisperseGoldResult disperseGold(ActivityInfo activityInfo, String manifesto) {
        ActivityDisperseGoldResult result = new ActivityDisperseGoldResult();
        if (activityInfo.getActivityId() != HuaShiGangMgr.getActivityInfo().getActivityId()) {
            result.setRet(GameErrorCode.E_ACTIVITY_OVER_TIME);
            return result;
        }
        if (!ActivityMgr.activityInTime(activityInfo)){
            result.setRet(GameErrorCode.E_ACTIVITY_OVER_TIME);
            return result;
        }
        List<Integer> decorationIdList = player.getModule(DecorationModule.class).getDecorationIdList(eDecorationType.HonoraryTitle.getValue());
        ActivityDisperseGoldInfo goldInfo = new ActivityDisperseGoldInfo();
        goldInfo.setActivityId(activityInfo.getActivityId());
        goldInfo.setType(activityInfo.getType());
        goldInfo.setUserId(player.getUserId());
        goldInfo.setManifesto(manifesto);
        goldInfo.setBeginTime(System.currentTimeMillis());
        goldInfo.setHonoraryTitles(StringUtils.listToString(decorationIdList, ","));
        goldInfo.setServerList(activityInfo.getServerIdList());
        goldInfo.setUserBaseInfo(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId()));
        result.setGoldInfo(goldInfo);
        return result;
    }

    /**
     * 获取花石纲活动系列，门客总赚钱（包含天赋技能加成）
     * @return
     */
    public long getPatronsAbility() {
        //门客列表
        List<UserPatrons> list = new ArrayList<>();
        for (UserPatrons pat : player.getModule(PatronsModule.class).getUserPatronsList()) {
            list.add(pat.cloneUserPatrons());
        }

        //天赋技能【八方来运】等，元夜闹东京不加
        ActivityInfo activityInfo = HuaShiGangMgr.getActivityInfo();
        if (activityInfo.getChildType() != eHuaShiGangActivityType.TokyoActivity.getValue()) {
            BattleManager.skillEffect(list);
        }

        //技能【替天行道】
        int bossTalentAddition = 0;
        for (UserPatrons patrons : list) {
            for (UserPatronsSkill patronsSkill : patrons.getSkillList()) {
                if (patronsSkill.getType() != ePatronsSkillType.Talent.getValue()) {
                    continue;
                }
                SkillInfo skillInfo = SkillMgr.getSkillInfo(patronsSkill.getSkillId());
                if (skillInfo.getType() == eSkillType.HuaShiGangBossDamageAddition.getValue()) {
                    bossTalentAddition += SkillMgr.getSkillAddition(skillInfo, patronsSkill.getSkillLv());
                }
            }
        }

        //计算门客总赚钱
        BigDecimal allAbility = new BigDecimal(0);
        for (UserPatrons userPatrons : list) {
            BigDecimal ability = new BigDecimal(userPatrons.getAbility());
            //算上天赋技能加成
            BigDecimal mulNum = BigDecimal.valueOf(userPatrons.getBattleAddition()).add(BigDecimal.valueOf(bossTalentAddition));//倍数
            ability = ability.multiply(mulNum.divide(BigDecimal.valueOf(1000)));
            allAbility = allAbility.add(ability);
        }
        return allAbility.longValue();
    }
}
